package hqu.jann.springsecurity.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//SpringSecurity相当于一个框架，解决了认证和授权的问题
@EnableWebSecurity // 开启WebSecurity模式
//WebSecurityConfigurerAdapter 是一个自定义security的策略 我们继承它来实现自己想要的认证和授权规则
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    //定义授权策略
    protected void configure(HttpSecurity http) throws Exception {
        // 首页所有人可以访问
        // 定义访问哪些网页需要哪些权限
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

       //没有权限就会自动进入登录页面
        http.formLogin().usernameParameter("username")
                .passwordParameter("password")
                //对应的表单提取数据
                .loginPage("/toLogin")
                //controller层

                .loginProcessingUrl("/login");
               //自带的验证 对应前端的表单提交路径
        http.csrf().disable();//关闭csrf

        //开启注销功能，注销成功之后会重定向到首页
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能，和前端的name相匹配
        http.rememberMe().rememberMeParameter("remember");
    }

    @Override
    //AuthenticationManagerBuilder 自定义认证策略

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       //分配用户名和密码以及对应的权限，密码进行加密处理

        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("Jann").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3");
    }
}
